package com.feidee.data.email.handler;

import com.feidee.data.email.model.EConstant;
import com.feidee.data.email.model.EmailLogModel;
import com.feidee.data.email.model.EmailProcessParam;
import com.feidee.data.email.process.EmailProcess;
import com.feidee.data.email.util.ApplicationContextUtil;
import com.feidee.data.email.util.EmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component("eventRunner")
public class EventRunner {

	private static BlockingQueue<EmailProcessParam> queue = new ArrayBlockingQueue<EmailProcessParam>(
			EConstant.QUERY_SIZE);
	private static ExecutorService executor = Executors.newFixedThreadPool(EConstant.EXECUTOR_THREAD_NUM);

	public void runReport() {
		try {
			EmailProcessParam processParam = queue.take();
			executor.submit(new ProcessThread(processParam));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void putEvent(EmailProcessParam param) {
		try {
			queue.put(param);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ProcessThread extends Thread {

	private EmailProcessParam emailProcessParam;
	private static Logger LOG = LoggerFactory.getLogger(ProcessThread.class);

	public ProcessThread(EmailProcessParam emailProcessParam) {
		setDaemon(true);
		this.emailProcessParam = emailProcessParam;
	}

	public void run() {
		EmailProcess emailProcess = ApplicationContextUtil.getBean(EmailProcess.class);
		if (emailProcess.isRunning(emailProcessParam.getEmail_key())) {
			LOG.info("邮件:" + emailProcessParam.getEmail_key() + " is running!");
			EmailLogModel logs = new EmailLogModel();
			logs.setEmail_key(emailProcessParam.getEmail_key());
			logs.setProcess("start");
			logs.setIndex(0);
			logs.setStatus("FAILED");
			logs.setMessage("邮件已经在运行!");
			logs.setCost(0);
			logs.setStarttime(EmailUtil.getNowTime());
			EmailUtil.sendLog(logs, "async");
		} else {
			LOG.info("邮件:" + emailProcessParam.getEmail_key() + " is ready to run!");
			EmailLogModel logs = new EmailLogModel();
			logs.setEmail_key(emailProcessParam.getEmail_key());
			logs.setProcess("start");
			logs.setIndex(0);
			logs.setStatus("SUCCESSFULLY");
			logs.setMessage("None");
			logs.setCost(0);
			logs.setStarttime(EmailUtil.getNowTime());
			EmailUtil.sendLog(logs, "async");
			emailProcess.putRunningMail(emailProcessParam.getEmail_key());
			emailProcess.process(emailProcessParam, "async");
			emailProcess.removeRunningMail(emailProcessParam.getEmail_key());
		}
	}
}
